﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CurrentCostLibrary;
using Communergy.Common.Events;
using Communergy.Common;


namespace Communergy.Labs.Reactive
{
    class Program
    {
        

        static void Main(string[] args)
        {
            

            RandomDataMonitorProvider randomData = new RandomDataMonitorProvider(2);
            randomData.EnergyReading += new Common.NewEnergyReadingHandler(random_EnergyReading);

            IObservable<IEvent<EnergyReadingEventArgs>> eventAsObservable = Observable.FromEvent(
                  (EventHandler<EnergyReadingEventArgs> ev) => ev,
                  ev => randomData.EnergyReading += ev,
                  ev => randomData.EnergyReading -= ev)
                  ;

            var bigData = from d in eventAsObservable                         
                          select d.EventArgs.EnergyMonitorOutput.SensorReadings.Where(e => e.SensorId ==0).FirstOrDefault().LiveReadings.Where(e=>e.AverageWatts>1000).FirstOrDefault()
                          ;

            //var s = eventAsObservable.Subscribe(
            //    data =>
            //        Console.WriteLine("subscribed {0}", data.EventArgs.EnergyMonitorOutput.SensorReadings[0].LiveReadings[0].AverageWatts)
            //        );


            var s = bigData.Subscribe
                (data =>
                    {
                        if (data != null)
                        {
                            Console.WriteLine("subscribed: {0}", data.AverageWatts);
                        }
                    });
            randomData.StartReadings();

            Console.ReadKey();
        }

        static void random_EnergyReading(object sender, Common.Events.EnergyReadingEventArgs re)
        {
            var output = re.EnergyMonitorOutput;
            var readings = from sensor in output.SensorReadings
                           from liveReadings in sensor.LiveReadings
                           select new
                               {
                                   sensor.SensorId,
                                   liveReadings.AverageWatts
                               };
            var readingsText = string.Join(", ", (from reading in readings
                                select string.Format("Sensor:{0}, Watts: {1}", reading.SensorId, reading.AverageWatts)).ToArray());

            Console.WriteLine(readingsText);
           // Console.WriteLine("Standard event. Watts: {0}",re.EnergyMonitorOutput.SensorReadings[0].LiveReadings[0].AverageWatts);
        }
    }
}
